/*Copyright (C) 2009 - 2011 MASSART GAUTHIER

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include <curl/curl.h>
#include "../headers.h"

short http_get_file(char *hote, char *file_path, char *save_path, short x, short y) {
	FILE *fichier_telecharge = fopen(save_path, "wb");
	CURL *session = curl_easy_init();
	short ret;

	if(session != NULL) {
		char adresse[150];
		sprintf(adresse, "http://%s%s", hote, file_path);
		if(curl_easy_setopt(session, CURLOPT_URL, adresse) == CURLE_OK) {
			if(curl_easy_setopt(session, CURLOPT_WRITEDATA, fichier_telecharge) == CURLE_OK) {
				if(curl_easy_setopt(session, CURLOPT_WRITEFUNCTION, fwrite) == CURLE_OK) {
					if(curl_easy_perform(session) == 0) {
						fclose(fichier_telecharge);
						curl_easy_cleanup(session);
						ret = 0;
					}
					else {
						ret = 1;
					}
				}
				else {
					ret = 1;
				}
			}
			else {
				ret = 1;
			}
		}
		else {
			ret = 1;
		}
	}
	else {
		ret = 1;
	}

	if(ret == 1) {
		fclose(fichier_telecharge);
		curl_easy_cleanup(session);
	}

	return ret;
}
